package cn.szabadsag.hrm.userdetails;

import cn.szabadsag.hrm.domain.LoginUser;
import cn.szabadsag.hrm.domain.Permission;
import cn.szabadsag.hrm.exception.Assert;
import cn.szabadsag.hrm.mapper.PermissionMapper;
import cn.szabadsag.hrm.service.ILoginUserService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yangcong
 * @date 2022年04月14日 18:57
 * @since
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private ILoginUserService loginUserService;

    @Autowired
    private PermissionMapper permissionMapper;

    /**
     *
     * @param username:用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //  1.根据用户名查询Login
        Assert.assertNotEmpty(username,"用户名不可为空！");
        //  2.查询数据库中的登录用户信息
        LoginUser loginUser = loginUserService.selectOne(new EntityWrapper<LoginUser>().eq("username", username));
        if (loginUser == null) throw new UsernameNotFoundException("用户没找到！");

        //  3.查询用户的权限
        List<Permission> permissions = permissionMapper.selectByUserId(loginUser.getId());
        //  4.map映射
        List<SimpleGrantedAuthority> authorities = permissions.stream()
                .map(permission -> new SimpleGrantedAuthority(permission.getSn()))
                .collect(Collectors.toList());

        String password = loginUser.getPassword();
        loginUser.setPassword(null);
        String login = JSON.toJSONString(loginUser);


        UserDetails userDetails = new User(
                login,   //  用户名
                password,    //  密码
                true,   //  账号启用
                true,   //  账户是否过期
                true,   //  密码是否过期
                true,   //  用户的权限
                authorities);
        return userDetails;
    }
}
